package com.shanhy.lixp.need001.startup;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.shanhy.lixp.need001.dao.ICompanyDao;
import com.shanhy.lixp.need001.model.Company;
import com.shanhy.lixp.need001.model.QichachaCompanyDetail;
import com.shanhy.lixp.need001.service.CompanyHtmlService;
import com.shanhy.lixp.need001.service.QichachaHtmlService;

/**
 * 系统启动执行
 * 
 * @author Shanhy
 *
 */
@Component
public class StartupRunner1 implements CommandLineRunner {

	private static final Logger LOG = LoggerFactory.getLogger(StartupRunner1.class);

	@Autowired
	private CompanyHtmlService companyHtmlService;

	@Autowired
	private QichachaHtmlService qichachaHtmlService;

	@Autowired
	private ICompanyDao companyDao;

	// 是否继续抓取HTML
	boolean continueFetchHtml = true;
	
	private static final String companyNameFilePath = "F:\\companyList.txt";
	private static final String companyDetailFilePath = "F:\\companyDetailList.txt";

	@Override
	public void run(String... arg0) throws Exception {
		// parserCompanyName();
		searchCompanyDetail();
	}

	/**
	 * 测试
	 */
	public void test() {
		QichachaCompanyDetail detail = qichachaHtmlService.getQichachaCompanyDetail("特变电工（德阳）电缆股份有限公司");
		LOG.info(detail.getBusinessScope());
	}
	
	/**
	 * 查询所有企业信息
	 */
	private void searchCompanyDetail() {
		
		try (Stream<String> lines = Files.lines(Paths.get(companyNameFilePath), StandardCharsets.UTF_8)) {
			lines.onClose(() -> System.out.println("Done!")).forEach(new Consumer<String>() {

				@Override
				public void accept(String companyName) {
					if(!continueFetchHtml)
						return;
					
					Company com = companyDao.getCompanyByName(companyName);
					if(com == null){
						// 新增
						com = new Company();
						com.setSname(companyName);
						
						QichachaCompanyDetail detail = qichachaHtmlService.getQichachaCompanyDetail(companyName);
						if (detail != null){ // 抓取到数据后，先保存再更新内容
							// 根据结果判定
							String errorCode = detail.getErrorCode();
							if(StringUtils.isBlank(errorCode)){// 成功
								companyDao.save(com);
								// 保存到数据库
								companyDao.updateCompany(detail.getId(), detail.getBusinessScope(), detail.getScontacts(), detail.getAddress(), com.getId());
							}else if("1".equals(errorCode)){
								// 持续爬去被限制，需要验证
								LOG.info("频繁抓取数据被限制，需要验证！");
								continueFetchHtml = false;
							}else if("2".equals(errorCode)||"3".equals(errorCode)){// 没有查询到结果
								companyDao.save(com);
								// 保存到数据库
								companyDao.updateCompany("", "", "", "没有查询到企业信息", com.getId());
							}
						}
					}
				}

			});
		} catch (IOException e) {
			e.printStackTrace();
		}

//		outputCompanyDetailFile(detailList);
	}

	/**
	 * 输出企业信息到文件
	 * 
	 * @param detailList
	 */
	public void outputCompanyDetailFile(List<QichachaCompanyDetail> detailList) {
		if (detailList == null)
			return;
		try {
			Path path = Paths.get(companyDetailFilePath);
			Files.deleteIfExists(path);
			Files.createFile(path);
			BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND);
			for (QichachaCompanyDetail company : detailList) {
				// writer.append(company.getName()).append("#-#").append(company.getBusinessScope());
				writer.append(company.getId()).append(",").append(company.getId());
				writer.newLine();
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			LOG.error("异常", e);
		}
	}

	/**
	 * 获取所有企业名称
	 */
	@SuppressWarnings("unchecked")
	public void parserCompanyName() {
		Map<String, Object> map = companyHtmlService.getCompanyListByHtml(1);
		if (map != null) {
			Object obj = map.get("list");
			if (obj != null && obj instanceof List) {
				List<Company> companyList = (List<Company>) obj;
				int totalPage = Integer.parseInt(map.get("totalPage").toString());
				for (int i = 2; i <= totalPage; i++) {
					Map<String, Object> tempMap = companyHtmlService.getCompanyListByHtml(i);

					if (tempMap != null) {
						Object tempObj = tempMap.get("list");
						if (tempObj != null && tempObj instanceof List) {
							List<Company> tempCompanyList = (List<Company>) tempObj;
							companyList.addAll(tempCompanyList);
						}
					}
				}

				outputCompanyNameFile(companyList);
			}
		}

	}

	/**
	 * 输出内容到文件
	 * 
	 * @param companyList
	 */
	private void outputCompanyNameFile(List<Company> companyList) {
		if (companyList == null)
			return;
		try {
			Path path = Paths.get(companyNameFilePath);
			Files.deleteIfExists(path);
			Files.createFile(path);
			BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND);
			for (Company company : companyList) {
				writer.append(company.getSname());
				writer.newLine();
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			LOG.error("异常", e);
		}
	}

}
